package com.xmtlxx.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDept;
import com.xmtlxx.common.core.domain.entity.SysDictData;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.Property;
import com.xmtlxx.oms.domain.Staging;
import com.xmtlxx.oms.domain.bo.TaskBo;
import com.xmtlxx.oms.domain.bo.TaskDtlBo;
import com.xmtlxx.oms.domain.vo.*;
import com.xmtlxx.oms.mapper.PropertyMapper;
import com.xmtlxx.oms.mapper.StagingMapper;
import com.xmtlxx.oms.mapper.TaskDtlMapper;
import com.xmtlxx.oms.mapper.TaskMapper;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.wms.domain.Inventory;
import com.xmtlxx.wms.domain.ProBase;
import com.xmtlxx.wms.domain.bo.InventoryBo;
import com.xmtlxx.wms.domain.bo.InventoryLogBo;
import com.xmtlxx.wms.domain.bo.SelectInventoryPropertyBo;
import com.xmtlxx.wms.domain.bo.StoreBo;
import com.xmtlxx.wms.domain.vo.*;
import com.xmtlxx.wms.mapper.InventoryMapper;
import com.xmtlxx.wms.mapper.StoreAreaMapper;
import com.xmtlxx.wms.mapper.StoreMapper;
import com.xmtlxx.wms.service.IInventoryLogService;
import com.xmtlxx.wms.service.IInventoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 库存Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class InventoryServiceImpl implements IInventoryService {

    private final InventoryMapper baseMapper;

    private final IInventoryLogService iInventoryLogService;

    private final PropertyMapper propertyMapper;

    private final StagingMapper stagingMapper;

    private final SysOssMapper sysOssMapper;

    private final TaskMapper taskMapper;

    private final SysDeptMapper sysDeptMapper;

    private final StoreMapper storeMapper;

    private final StoreAreaMapper areaMapper;

    private final TaskDtlMapper taskDtlMapper;

    /**
     * 查询库存
     *
     * @param id 库存主键
     * @return 库存
     */
    @Override
    public InventoryVo queryById(String id) {
        //return baseMapper.selectVoById(id);
        InventoryVo vo = baseMapper.selectInventoryVoByID(id);
        SysOssBo ossBo = new SysOssBo();
        ossBo.setBuss("property");
        ossBo.setObjid(vo.getPno());
        vo.setOss(sysOssMapper.selectPropertySysOssList(ossBo));
        return vo;
    }

    @Override
    public InventoryVo queryByPno(String pno, String storeId, String status) {

        LambdaQueryWrapper<Inventory> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(pno), Inventory::getPno, pno);
        lqw.eq(StringUtils.isNotBlank(storeId), Inventory::getStoreId, storeId);
        lqw.eq(StringUtils.isNotBlank(status), Inventory::getStatus, status);
        Inventory inventory = baseMapper.selectOne(lqw);
        InventoryVo vo = null;
        if (inventory != null) {
            vo = new InventoryVo();
            BeanUtil.copyProperties(inventory, vo);
            SysOssBo ossBo = new SysOssBo();
            ossBo.setObjid(vo.getPno());
            vo.setOss(sysOssMapper.selectPropertySysOssList(ossBo));
        }
        return vo;
    }

    @Override
    public InventoryVo selectByPno(String pno) {

        InventoryVo vo = baseMapper.selectInventoryVoByPno(pno);
        SysOssBo ossBo = new SysOssBo();
        ossBo.setObjid(vo.getPno());
        vo.setOss(sysOssMapper.selectPropertySysOssList(ossBo));
        return vo;

    }

    /**
     * 查询库存列表
     *
     * @param bo 库存
     * @return 库存
     */
    @Override
    public TableDataInfo<InventoryVo> queryPageList(InventoryBo bo, PageQuery pageQuery) {
        // LambdaQueryWrapper<Inventory> lqw = buildQueryWrapper(bo);
        // Page<InventoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<InventoryVo> result = baseMapper.selectPageInventoryList(pageQuery.build(), bo);
        if (result != null && result.getRecords() != null && result.getRecords().size() > 0) {
            result.getRecords().forEach(item -> {
                SysOssBo ossBo = new SysOssBo();
                ossBo.setBuss("property");
                ossBo.setObjid(item.getPno());
                item.setOss(sysOssMapper.selectSysOssList(ossBo));
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询库存列表
     *
     * @param bo 库存
     * @return 库存
     */
    @Override
    public List<InventoryVo> queryList(InventoryBo bo) {

        SysDept dept = sysDeptMapper.selectById(LoginHelper.getDeptId());
        if (dept != null && StringUtils.isNotBlank(dept.getDeptCode())) {
            if (dept.getDeptCode().startsWith("3504")) {
                bo.setIsSecurity("1");
            }
        }
        List<InventoryVo> result = baseMapper.selectInventoryList(bo);
        if (result != null && result.size() > 0) {
            result.forEach(item -> {
                SysOssBo ossBo = new SysOssBo();
                ossBo.setBuss("property");
                ossBo.setObjid(item.getPno());
                item.setOss(sysOssMapper.selectSysOssList(ossBo));
            });
        }
        return result;
    }

    @Override
    public TableDataInfo<InventoryVo> queryPageAppList(InventoryBo bo, PageQuery pageQuery) {

        SysDept dept = sysDeptMapper.selectById(LoginHelper.getDeptId());
        if (dept != null && StringUtils.isNotBlank(dept.getDeptCode())) {
            if (dept.getDeptCode().startsWith("3504")) {
                bo.setIsSecurity("1");
            }
        }
        Page<InventoryVo> result = baseMapper.selectPageInventoryList(pageQuery.build(), bo);
        if (result != null && result.getRecords() != null && result.getRecords().size() > 0) {
            result.getRecords().forEach(item -> {
                SysOssBo ossBo = new SysOssBo();
                ossBo.setBuss("property");
                ossBo.setObjid(item.getPno());
                item.setOss(sysOssMapper.selectSysOssList(ossBo));
            });
        }
        return TableDataInfo.build(result);
    }

    @Override
    public List<InventoryVo> queryListWithOutPic(InventoryBo bo) {

        return baseMapper.selectInventoryList(bo);
    }

    @Override
    public List<InventoryVo> selectInventoryProList(InventoryBo bo) {
        return baseMapper.selectInventoryProList(bo);
    }

    private LambdaQueryWrapper<Inventory> buildQueryWrapper(InventoryBo bo) {

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Inventory> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getStoreId()), Inventory::getStoreId, bo.getStoreId());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), Inventory::getAreaId, bo.getAreaId());
        lqw.eq(StringUtils.isNotBlank(bo.getLocatorId()), Inventory::getLocatorId, bo.getLocatorId());
        lqw.eq(StringUtils.isNotBlank(bo.getPno()), Inventory::getPno, bo.getPno());
        lqw.eq(StringUtils.isNotBlank(bo.getRfid()), Inventory::getRfid, bo.getRfid());
        lqw.like(StringUtils.isNotBlank(bo.getName()), Inventory::getName, bo.getName());
        lqw.between(params.get("beginIntime") != null && params.get("endIntime") != null,
                Inventory::getIntime, params.get("beginIntime"), params.get("endIntime"));
        lqw.between(params.get("beginLastTime") != null && params.get("endLastTime") != null,
                Inventory::getLastTime, params.get("beginLastTime"), params.get("endLastTime"));
        lqw.between(params.get("beginNextTime") != null && params.get("endNextTime") != null,
                Inventory::getNextTime, params.get("beginNextTime"), params.get("endNextTime"));
        lqw.eq(bo.getDeptId() != null, Inventory::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Inventory::getStatus, bo.getStatus());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
                Inventory::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null,
                Inventory::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateBy()), Inventory::getUpdateBy, bo.getUpdateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), Inventory::getCreateBy, bo.getCreateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Inventory::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增库存
     *
     * @param bo 库存
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(InventoryBo bo) {

        Inventory add = BeanUtil.toBean(bo, Inventory.class);
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean insertByStagingBo(InventoryBo bo) {

        boolean flag = true;
        Inventory inventory = new Inventory();
        Staging staging = stagingMapper.selectById(bo.getStagingId());
        if (ObjectUtil.isNotNull(staging) && StringUtils.isNotEmpty(staging.getId())) {
            Long before = 0L;
            Long nums = staging.getReceiveNums();
            Long afters = 0L;
            Long initnums = 0L;
            //判断当前移交登记是否有记录
            InventoryLogVo logVo = iInventoryLogService.queryByReferId(null, staging.getId());

            if (ObjectUtil.isNull(logVo) || StringUtils.isEmpty(logVo.getId())) {
                //判断当前仓库是否有该物品编号
                InventoryVo vo = this.queryByPno(staging.getPno(), staging.getStoreId(), "0");

                if (ObjectUtil.isNotNull(vo) && StringUtils.isNotEmpty(vo.getId())) {
                    BeanUtil.copyProperties(vo, inventory);
                    before = inventory.getNums();
                    initnums = inventory.getInnums() + nums;
                    afters = initnums;
                    saveInventoryLog(inventory, before, nums, afters, bo.getStagingId(), "0");
                    if (staging.getType().equals("1")) {//调用
                        before = initnums;
                        afters = afters - nums;
                        saveInventoryLog(inventory, before, nums, afters, bo.getStagingId(), "1");
                    }
                    inventory.setInnums(initnums);
                    inventory.setNums(afters);

                } else {
                    BeanUtil.copyProperties(staging, inventory, "id");
                    initnums = nums;
                    afters = nums;
                    inventory.setId(IdUtil.simpleUUID());
                    inventory.setIntime(new Date());

                    saveInventoryLog(inventory, before, nums, afters, bo.getStagingId(), "0");
                    if (staging.getType().equals("1")) {//调用
                        before = initnums;
                        afters = afters - nums;
                        saveInventoryLog(inventory, before, nums, afters, bo.getStagingId(), "1");
                    }

                    inventory.setInnums(initnums);
                    inventory.setNums(afters);

                }
                flag = baseMapper.insertOrUpdate(inventory);
            }
        }

        return flag;
    }

    /**
     * 修改库存
     *
     * @param bo 库存
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(InventoryBo bo) {

        Inventory update = BeanUtil.toBean(bo, Inventory.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Inventory entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除库存
     *
     * @param ids 需要删除的库存主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addInventory(InventoryBo bo) {

        LambdaQueryWrapper<Inventory> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getStoreId()), Inventory::getStoreId, bo.getStoreId());
        lqw.eq(StringUtils.isNotBlank(bo.getPno()), Inventory::getPno, bo.getPno());
        //查询库存是否存在该物品
        Inventory enty = baseMapper.selectOne(lqw);

        boolean flag = false;
        Long befores = 0L;
        Long nums = 0L;
        Long afters = 0L;
        String id = null;
        String status = null;
        //判断当前上架任务是否重复提交库存
        if (enty == null) {
            Inventory add = BeanUtil.toBean(bo, Inventory.class);
            validEntityBeforeSave(add);
            add.setIntime(new Date());
            add.setInnums(bo.getNums());
            add.setNums(bo.getNums());
            add.setUnit(bo.getUnit());
            add.setOutnums(0L);
            add.setDeals(0L);
            add.setTnums(0L);
            add.setRnums(0L);
            add.setEoutnums(0L);
            add.setEtnums(0L);
            add.setStatus("0");
            //填充UUID
            add.setId(IdUtil.simpleUUID());
            add.setDelFlag("0");
            if (StringUtils.isBlank(add.getCreateBy())) {
                add.setCreateBy("Sadmin");
            }
            flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
            nums = bo.getNums();
            afters = add.getNums();
            id = add.getId();
        } else {
            //0.增加库存，1.减少库存
            if (bo.getMark().equals("0")) {
                befores = enty.getInnums();
                nums = bo.getNums();
                afters = nums + befores;
                switch (bo.getPutTaskType()) {
                    case "1":
                        enty.setNums(enty.getNums() + bo.getNums());
                        Long tnums = enty.getTnums();//调用数
                        tnums = tnums - bo.getNums();//获取剩余调用数
                        Long rnums = enty.getRnums();//归还数
                        rnums = enty.getRnums() + bo.getNums();//获取剩余归还数
                        enty.setTnums(tnums);
                        enty.setRnums(rnums);
                        if (tnums == 0L) {
                            status = "0";
                        }
                        break;
                    default:

                        Long transfers = enty.getTnums() != null ? enty.getTnums() : 0L;
                        Long deals = enty.getDeals() != null ? enty.getDeals() : 0L;
                        Long returnNums = enty.getRnums() != null ? enty.getRnums() : 0L;

                        enty.setIntime(new Date());
//                        enty.setInnums(enty.getInnums()+bo.getNums());
//                        enty.setNums(enty.getNums()+bo.getNums());
                        enty.setInnums(bo.getNums());
                        Long realNums = bo.getNums() - transfers - deals + returnNums;
                        enty.setNums(realNums);
                        status = "0";
                        break;
                }

                //同步更新到property
                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, bo.getPno()));
                property.setInnums(enty.getInnums());
                property.setOutnums(enty.getOutnums());
                property.setDeals(enty.getDeals());
                property.setTnums(enty.getTnums());
                property.setRnums(enty.getRnums());
                property.setNums(enty.getNums());
                property.setLocatorId(bo.getLocatorId());
                propertyMapper.updateById(property);

            } else if (bo.getMark().equals("1")) {

                befores = enty.getNums();
                nums = bo.getNums();
                afters = nums - befores;
                enty.setNums(enty.getNums() - bo.getNums());

                //0-出库 1-调用 2-处置
                switch (bo.getPickType()) {
                    case "0":
                        Long outnums = 0L;
                        if (enty.getOutnums() != null) {
                            outnums = enty.getOutnums();
                        }
//                        enty.setOutnums(outnums + bo.getNums());
                        //取证出库
                        if (StringUtils.isNotBlank(bo.getEvidence()) && bo.getEvidence().equals("1")) {
                            enty.setEoutnums(outnums + bo.getNums());
                        } else {
                            enty.setOutnums(outnums + bo.getNums());
                        }
                        status = "1";
                        break;
                    case "1":
                        Long tnums = 0L;
                        if (enty.getTnums() != null) {
                            tnums = enty.getTnums();
                            //归还数 置为0
                            enty.setRnums(0L);
                        }
//                        enty.setTnums(tnums + bo.getNums());
                        //取证调用
                        if (StringUtils.isNotBlank(bo.getEvidence()) && bo.getEvidence().equals("1")) {
                            enty.setEoutnums(tnums + bo.getNums());
                        } else {
                            enty.setTnums(tnums + bo.getNums());
                        }

                        /**
                         * 预防问题：当挑拣任务未完成，已有调用归还单进行物品归还；状态默认不改变
                         */
                        if (StringUtils.isNotBlank(bo.getTid())) {
                            TaskBo taskBo = new TaskBo();
                            taskBo.setReturnId(bo.getTid());
                            TaskVo task = taskMapper.selectTaskVoByTaskNo(taskBo);

                            if (task == null) {
                                status = "2";
                            }
                        } else {
                            status = "2";
                        }

                        break;
                    case "2":
                        Long deals = 0L;
                        if (enty.getDeals() != null) {
                            deals = enty.getDeals();
                        }
                        enty.setDeals(deals + bo.getNums());
                        status = "3";
                        break;
                }

                //同步更新到property
                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, bo.getPno()));
                property.setInnums(enty.getInnums());
                property.setOutnums(enty.getOutnums());
                property.setDeals(enty.getDeals());
                property.setTnums(enty.getTnums());
                property.setRnums(enty.getRnums());
                property.setNums(enty.getNums());
                property.setLocatorId(bo.getLocatorId());
                propertyMapper.updateById(property);
            }
            //修复再次入库库存表库位没修改问题
            enty.setStoreId(bo.getStoreId());
            enty.setAreaId(bo.getAreaId());
            enty.setLocatorId(bo.getLocatorId());
            enty.setQrcode(bo.getQrcode());
            enty.setStatus(status);
            baseMapper.updateById(enty);
            id = enty.getId();
        }


        //生成入库记录
        InventoryLogBo logBo = new InventoryLogBo();
        logBo.setStockId(id);
        logBo.setBefores(befores);
        logBo.setNums(nums);
        logBo.setAfters(afters);
        logBo.setType(status);//0：入库；1：出库 2:调用 3：处置
        logBo.setReferId(bo.getTaskId());
        logBo.setStoreId(bo.getStoreId());
        if (LoginHelper.checkLoginUser()) {
            logBo.setOperator(LoginHelper.getNickname());
        }
        logBo.setDeptId(bo.getDeptId());
        logBo.setStatus("0");
        logBo.setMemo(bo.getRemark());
        logBo.setDelFlag("0");
        flag = iInventoryLogService.insertByBo(logBo);

        //更新财物信息
//        PropertyBo propertyBo = new PropertyBo();
//        propertyBo.setUpdatePno(bo.getPno());
//        PropertyVo propertyVo = propertyMapper.selectPropertyVo(propertyBo);
//        if(propertyVo != null){
//            Property property = new Property();
//            BeanUtils.copyProperties(propertyVo,property);
//            property.setLocatorId(bo.getLocatorId());
//            propertyMapper.updateById(property);
//        }

        return flag;
    }

    @Override
    public List<DataVo> selectInventoryByList() {

        return baseMapper.selectInventoryByList();
    }

    @Override
    public List<DataVo> selectPropertyByList() {

        return baseMapper.selectInventoryByClassfy();
    }

    @Override
    public List<InventoryVo> queryInventoryByList() {

        return baseMapper.queryInventoryByList();
    }

    @Override
    public List<StoreBiVo> selectCountByStore(InventoryBo inventory, List<SysDictData> dictDataList) {

        List<StoreBiVo> items = new ArrayList<>();
        StoreBo storeBo = new StoreBo();
        if (StringUtils.isNotBlank(inventory.getStoreId())) {
            storeBo.setId(inventory.getStoreId());
        }
        if (StringUtils.isNotBlank(inventory.getAreaId())) {
            StoreAreaVo areaVo = areaMapper.selectStoreAreaVoByID(inventory.getAreaId());
            storeBo.setId(areaVo.getStoreId());
        }
        List<StoreVo> storeVos = storeMapper.selectStoreList(storeBo);
        InventoryBo param = BeanUtil.copyProperties(inventory, InventoryBo.class);
        for (StoreVo store : storeVos) {
            param.setStoreId(store.getId());
            List<StoreBiVo> storeBiVos = baseMapper.selectCountByStore(param);
            if (storeBiVos == null || storeBiVos.size() == 0) {
                storeBiVos = new ArrayList<>();
                StoreBiVo biVo = new StoreBiVo();
                biVo.setStoreName(store.getName());
                biVo.setInnums(0L);
                biVo.setNums(0L);
                biVo.setOutnums(0L);
                biVo.setDeals(0L);
                biVo.setTnums(0L);
                biVo.setRnums(0L);
                biVo.setEoutnums(0L);
                biVo.setEtnums(0L);
                biVo.setId(store.getId());
                biVo.setRegion(param.getRegion());
                storeBiVos.add(biVo);
            }
            List<StoreBiVo> tempList = new ArrayList<>(storeBiVos);
            if (StringUtils.isEmpty(param.getRegion())) {
                dictDataList.forEach(dict -> {
                    List<StoreBiVo> storeBis = tempList.stream().filter(s -> s.getRegion()!=null && s.getRegion().equals(dict.getDictValue())).collect(Collectors.toList());
                    if (storeBis == null || storeBis.size() == 0) {
                        StoreBiVo biVo = new StoreBiVo();
                        biVo.setStoreName(store.getName());
                        biVo.setInnums(0L);
                        biVo.setNums(0L);
                        biVo.setOutnums(0L);
                        biVo.setDeals(0L);
                        biVo.setTnums(0L);
                        biVo.setRnums(0L);
                        biVo.setEoutnums(0L);
                        biVo.setEtnums(0L);
                        biVo.setId(store.getId());
                        biVo.setRegion(dict.getDictValue());
                        tempList.add(biVo);
                    }

                });
            }
            for (StoreBiVo vo : tempList) {
                InventoryBo bo = new InventoryBo();
                bo.setStoreId(vo.getId());
                bo.setRegion(vo.getRegion());
                bo.setXzType(inventory.getXzType());
                StoreBiVo counts = baseMapper.storeReceivesAndUnPuts(bo);
//                StoreBiVo unputs = baseMapper.storeUnPuts(bo);
                log.info("Region::" + JsonUtils.toJsonString(vo));
                if (counts != null) {
                    log.info("Counts::" + JsonUtils.toJsonString(counts));
//                    vo.setReceives(counts.getReceives() != null ? counts.getReceives() : 0L);
                    Long receives = (counts.getReceives() != null ? counts.getReceives() : 0L) + (counts.getReceivesOrder() != null ? counts.getReceivesOrder() : 0L);
                    vo.setReceives(receives);
                    Long unputs = counts.getUnputs() != null ? counts.getUnputs() : 0L;
                    Long trads = counts.getTrads() != null ? counts.getTrads() : 0L;
                    vo.setUnputs(unputs + trads);
                }
//                if(unputs != null){
//                    vo.setUnputs(unputs.getUnputs() != null ? unputs.getUnputs() : 0L);
//                }
            }
            items.addAll(tempList);
        }
        return items;
    }

    @Override
    public List<StoreBiVo> selectCountByStoreApp(InventoryBo inventory) {

        List<StoreBiVo> items = baseMapper.selectCountByAppStore(inventory);
        if (items != null && items.size() > 0) {
            for (StoreBiVo vo : items) {
                InventoryBo bo = new InventoryBo();
                bo.setStoreId(vo.getId());
                bo.setRegion(vo.getRegion());
                StoreBiVo counts = baseMapper.storeReceivesAndUnPuts(bo);
//                StoreBiVo unputs = baseMapper.storeUnPuts(bo);
                if (counts != null) {
                    Long receives = (counts.getReceives() != null ? counts.getReceives() : 0L) + (counts.getReceivesOrder() != null ? counts.getReceivesOrder() : 0L);
                    vo.setReceives(receives);
                    Long unputs = counts.getUnputs() != null ? counts.getUnputs() : 0L;
                    Long trads = counts.getTrads() != null ? counts.getTrads() : 0L;
                    vo.setUnputs(unputs + trads);
                }
//                if(unputs != null){
//                    vo.setUnputs(unputs.getUnputs() != null ? unputs.getUnputs() : 0L);
//                }
            }
        }
        return items;
    }

    @Override
    public List<AreaBiVo> selectCountByArea(InventoryBo inventory) {

        return baseMapper.selectCountByArea(inventory);
    }

    @Override
    public List<RegionBiVo> selectCountByRegion(InventoryBo inventory) {

        return baseMapper.selectCountByRegion(inventory);
    }

    @Override
    public List<RegionBiVo> selectCountByRegionApp(InventoryBo inventory) {

        return baseMapper.selectCountByAppRegion(inventory);
    }

    @Override
    public CurrentBiVo countCurrentTotals(InventoryBo inventory) {

        return baseMapper.countCurrentTotals(inventory);
    }

    @Override
    public CurrentBiVo countPickupTotals(InventoryBo inventory) {

        return baseMapper.countPickupTotals(inventory);
    }

    @Override
    public CurrentBiVo countPoliceTotals() {

        return baseMapper.countPoliceTotals();
    }

    @Override
    public List<RegionBiVo> countPoliceDatas() {

        return baseMapper.countPoliceDatas();
    }

    @Override
    public List<CurrentBiVo> countRegionTotals() {

        return baseMapper.countRegionTotals();
    }

    @Override
    public List<CurrentBiVo> countPoliceDeptTotals() {

        return baseMapper.countPoliceDeptTotals();
    }

    @Override
    public CurrentBiVo countCurrentOutTotals(InventoryBo inventory) {

        return baseMapper.countCurrentOutTotals(inventory);
    }

    @Override
    public CurrentBiVo countDatasTotals(InventoryBo inventory) {

        return baseMapper.countDatasTotals(inventory);
    }

    @Override
    public CurrentBiVo countDatasCurrentTotals(InventoryBo inventory) {

        return baseMapper.countDatasCurrentTotals(inventory);
    }

    @Override
    public List<RegionBiVo> selectCountByCarType(InventoryBo inventory) {

        List<RegionBiVo> list = baseMapper.countCarTypes(inventory);
        List<RegionBiVo> result = new ArrayList<>();
        if (list != null && list.size() > 0) {
            list.forEach(item -> {
                if (item.getCno().equals("X1") || item.getCno().equals("X2")) {
                    item.setCno("X");
                }
                boolean had = false;
                if (result != null && result.size() > 0) {
                    for (RegionBiVo r : result) {
                        if (r.getCno().equals(item.getCno()) && r.getRegion().equals(item.getRegion())) {
                            r.setNums((item.getNums() != null ? item.getNums() : 0) + (r.getNums() != null ? r.getNums() : 0));
                            r.setInnums((item.getInnums() != null ? item.getInnums() : 0) + (r.getInnums() != null ? r.getInnums() : 0));
                            r.setOutnums((item.getOutnums() != null ? item.getOutnums() : 0) + (r.getOutnums() != null ? r.getOutnums() : 0));
                            r.setDeals((item.getDeals() != null ? item.getDeals() : 0) + (r.getDeals() != null ? r.getDeals() : 0));
                            r.setTnums((item.getTnums() != null ? item.getTnums() : 0) + (r.getTnums() != null ? r.getTnums() : 0));
                            r.setRnums((item.getRnums() != null ? item.getRnums() : 0) + (r.getRnums() != null ? r.getRnums() : 0));
                            r.setEoutnums((item.getEoutnums() != null ? item.getEoutnums() : 0) + (r.getEoutnums() != null ? r.getEoutnums() : 0));
                            r.setEtnums((item.getEtnums() != null ? item.getEtnums() : 0) + (r.getEtnums() != null ? r.getEtnums() : 0));
                            had = true;
                        }
                    }
                }
                if (!had) {
                    result.add(item);
                }
            });
        }
        return result;
    }

    @Override
    public List<InventoryVo> reCheckInventoryDatas() {

        InventoryBo bo = new InventoryBo();
        List<InventoryVo> list = baseMapper.selectInventoryList(bo);
        List<InventoryVo> result = new ArrayList<>();
        List<String> taskNos = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (InventoryVo item : list) {
                TaskDtlBo taskDtlBo = new TaskDtlBo();
                taskDtlBo.setDelFlag("0");
                taskDtlBo.setPno(item.getPno());
                List<TaskDtlVo> dtls = taskDtlMapper.selectTaskDtlList(taskDtlBo);
                Long innums = 0L;
                Long outnums = 0L;
                Long tnums = 0L;
                Long rnums = 0L;
                Long deals = 0L;
                Long eoutnums = 0L;
                Long etnums = 0L;
                Long nums = 0L;

                if (dtls != null && dtls.size() > 0) {
                    for (TaskDtlVo dtl : dtls) {
                        if (dtl.getTaskType().equals("2")) {
                            continue;
                        }
                        log.info(JsonUtils.toJsonString(dtl));
                        if (dtl.getTaskType().equals("0")) {
                            nums += dtl.getNums();
                        } else {
                            nums -= dtl.getNums();
                        }
                    }
                }
                if (!nums.equals(item.getNums())) {
                    result.add(item);
                }
            }
        }
        return result;
    }

    private QueryWrapper<Object> getSelectInventoryPropertyQueryBuild(SelectInventoryPropertyBo bo) {

        return new QueryWrapper<>().func(i -> {
            i.eq(StrUtil.isNotBlank(bo.getPno()), "I.PNO", bo.getPno());
            i.eq(StrUtil.isNotBlank(bo.getStoreName()), "S.NAME", bo.getStoreName());
        });
    }


    @Override
    public TableDataInfo<SelectInventoryPropertyBo> selectInventoryPropertyList(PageQuery pageQuery, SelectInventoryPropertyBo bo) {

        return TableDataInfo.build(baseMapper.selectInventoryPropertyList(pageQuery.build(),
                getSelectInventoryPropertyQueryBuild(bo)));
    }

    @Override
    public boolean tempStorage(List<String> ids) {

        List<Inventory> inventoryList = ids.stream().map(id -> {
            Inventory inventory = new Inventory();
            inventory.setId(id);
            inventory.setStatus("9");
            inventory.setTempStorageTime(new Date());
            return inventory;
        }).collect(Collectors.toList());

        if (!baseMapper.updateBatchById(inventoryList)) {
            throw new ServiceException("更新暂存财物异常");
        }

        return true;
    }

    @Override
    public boolean cancelTempStorage(List<String> ids) {

        return baseMapper.update(new Inventory(), new LambdaUpdateWrapper<Inventory>().set(Inventory::getTempStorageTime, null)
                .set(Inventory::getStatus, 0).in(Inventory::getId, ids)) > 0;
    }

    private void saveInventoryLog(Inventory inventory, Long before, Long nums, Long afters, String stagingId, String type) {

        InventoryLogBo bo = new InventoryLogBo();
        bo.setStockId(inventory.getId());
        bo.setStoreId(inventory.getStoreId());
        bo.setDeptId(inventory.getDeptId());
        bo.setReferId(stagingId);
        bo.setBefores(before);
        bo.setNums(nums);
        bo.setAfters(afters);
        bo.setType(type);
        if (LoginHelper.checkLoginUser()) {
            bo.setOperator(LoginHelper.getNickname());
        }
        bo.setStatus("0");
        iInventoryLogService.insertByBo(bo);
    }

    @Override
    public List<ProBase> getProBaseList() {
        return baseMapper.getProBaseList();
    }

    @Override
    public int insertProBase(List<ProBase> proBases) {
        return baseMapper.insertProBase(proBases);
    }
}
